//
//  ViewController.swift
//  AlipayDemo2
//
//  Created by dengwei on 15/11/12.
//  Copyright © 2015年 dengwei. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    var TicketTotalprice:Float=0.01;//支付金额
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //申明按钮
        let but = UIButton(type: UIButtonType.System);
        but.setTitle("支付宝支付", forState: UIControlState.Normal)
        but.backgroundColor = UIColor.greenColor()
        but.frame = CGRect(x: 10, y: 100, width: 100, height: 30)
        but.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
            self.view.addSubview(but);
    }
    
    func click()
    {
        //调用接口
        AliplayFunc();
        print("click")
    }
    //支付宝接口
    func AliplayFunc(){
        let Orders = Order()
        Orders.partner = AlipayConfig.partner
        Orders.seller = AlipayConfig.seller
        Orders.productName = "玩充充游戏下单"
        Orders.productDescription = "this is a goods"
        Orders.amount = NSString(format: "%.2f",TicketTotalprice) as String ;//（价格必须小数点两位）
        Orders.tradeNO = Order.generateTradeNO()
        Orders.notifyURL = "";//
        Orders.service = "mobile.securitypay.pay"
        Orders.paymentType = "1"
        Orders.inputCharset = "utf-8"
        Orders.itBPay = "30m"
        Orders.showUrl = "m.alipay.com"
        let appScheme = "AlipayDemo"
        let orderSpec = Orders.description;
        let signer = CreateRSADataSigner(AlipayConfig.privateKey);
        let signedString = signer.signString(orderSpec);
        let orderString = "\(orderSpec)&sign=\"\(signedString)\"&sign_type=\"RSA\"";
        AlipaySDK.defaultService().payOrder(orderString, fromScheme: appScheme, callback: { (resultDic) -> Void in
            print("reslut = \(resultDic)");
            if let Alipayjson = resultDic as? NSDictionary{
                let resultStatus = Alipayjson.valueForKey("resultStatus") as! String
                if resultStatus == "9000"{
                    print("OK")
                }else if resultStatus == "8000" {
                    print("正在处理中")
                    self.navigationController?.popViewControllerAnimated(true)
                }else if resultStatus == "4000" {
                    print("订单支付失败");
                    self.navigationController?.popViewControllerAnimated(true)
                }else if resultStatus == "6001" {
                    print("用户中途取消")
                    self.navigationController?.popViewControllerAnimated(true)
                }else if resultStatus == "6002" {
                    print("网络连接出错")
                    self.navigationController?.popViewControllerAnimated(true)
                }
            }
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

